Ext.define('FirstMate.store.Tides', {
	requires : ['FirstMate.model.Tide'],
	extend : 'Ext.data.Store',
	pageNumber : 0,
	callsProcessed : 0,
	firstLoad : true,

	config : {
		grouped : true,
		grouper : {
			groupFn : function (record){
				return record.get('stationName');
			}		
		},		
		storeId: 'tidesStore',	   
		model : 'FirstMate.model.Tide',
		clearOnPageLoad : false,
		pageSize : 0
	},
	
	loadAll : function(time){
	
		this.fireEvent("allTideDataLoading");
		//console.log("loading: " + time);
		if (!this.firstLoad){
			 this.getProxy().abort();
			 this.firstLoad = false;
		};
		this.removeAll();
		this.pageNumber == 0;
		this.callsProcessed == 0;
		var stationsStore  = Ext.getStore('tidesStationsStore');
		stationsStore.each(function (record){
			this.__loadTides(record.get("StationID"),time);
		},this);
		if (stationsStore.getCount() === 0){
			this.fireEvent("allTideDataLoaded");
		};
	},
	
	//Private
	__loadTides : function (stationID,time){
		
		var mintim = new Date (time.getTime());
		var maxtim = new Date (time.getTime());
		maxtim.setDate(maxtim.getDate()+1);
		//this.log(position,minlat,maxlat,minlng,maxlng,mintim,maxtim);
		this.setProxy(	
				{
					type: 'jsonp',
					callbackKey : '.jsonp',
					autoAppendParams : false,
					enablePagingParams : false,
					noCache : false,                               
					url : 'http://coastwatch.pfeg.noaa.gov/erddap/tabledap/nosCoopsWLTPHL.json?' +
					'stationID,stationName,longitude,latitude,time,waterLevel,type' +
					'&stationID=' + '\"' + stationID + '\"' +
					'&distinct()' +
					'&time%3E=' + mintim.toISOString() +
					'&time%3C=' + maxtim.toISOString(),
					reader: new Ext.data.reader.Array({
						type: 'json',
						rootProperty: 'table.rows'
					})
				}
				
		);
		this.pageNumber++;
		//console.log('loading page :' + this.pageNumber);
		this.loadPage(this.pageNumber,{
		    callback: function(records, operation, success) {
		        // the operation object contains all of the details of the load operation
		    	this.callsProcessed++;
		//    	console.log('got success       : ' + success);
		    	if (success == true){			    	
		    		this.add(records);
		//	    	console.log('page number :  ' + this.pageNumber);
		    	}
		    	//TODO else
		    	if (this.callsProcessed == this.pageNumber){
		    		this.sort([
		    		           {
		    		               property : 'stationName'
		    		           },
		    		           {
		    		               property : 'time'
		    		           }
		    		       ]);
		    		this.fireEvent("allTideDataLoaded");
		    	}
		    },
		    scope: this
		});
	}
});

